<template>
  <div>
    <PageTitleSearch
      :title="title"
      :hotelList="hotelList"
      :currentHotel="currentHotel"
      v-model:lastMonth="lastMonth"
      :currentAcc="currentAcc"
      @hotel-change="handleSelectChange"
      @date-change="handleDateSelect"
      @acc-change="handleAccSelect"
    />
    <div class="main-content">
      <RankingTable :dataList="tableList" :columns="dataColumns" :loading="loading" :summary="summaryData" :main-title="'客房数据'" :sub-title="''" />
    </div>
    <ReportRemarkCard title="说明" :loading="loading" :reportCode="reportCode" :reportName="reportName" />
  </div>
</template>
<script>
  import { defHttp } from '/@/utils/http/axios';
  import * as MathUtil from '/@/utils/MathUtil';
  import * as Constant from '/@/utils/Constant';
  import PageTitleSearch from '@/views/applications/ui/PageTitleSearch.vue';
  import dayjs from 'dayjs';
  // import FlexCard from "@/views/applications/ui/FlexCard.vue";
  import ReportRemarkCard from '@/views/applications/ui/ReportRemarkCard.vue';
  // import TableCard from "@/views/applications/ui/TableCard.vue";
  import RankingTable from '@/views/applications/ui/RankingTable.vue';
  const REPORT_NAME = '酒店月度公司客户（项目）';
  const REPORT_CODE = 'hotel-month-single-company';
  const APIS = {
    month: 'getHotelMonthCompany',
    year: 'getHotelMonthAccCompany',
  };
  const INCOME_APIS = {
    month: 'getHotelMonthRoomIncome',
    year: 'getHotelMonthAccRoomIncome',
  };

  export default {
    name: REPORT_NAME,

    components: {
      PageTitleSearch,
      // FlexCard,
      ReportRemarkCard,
      // TableCard,
      RankingTable,
    },

    data() {
      return {
        title: '客房部分-公司客户',
        reportCode: '',
        reportName: '',
        loading: false,
        competLoading: false,
        tableHigh: { x: '100%', y: 400 },
        lastMonth: dayjs().subtract(1, 'month').format('YYYYMM'),
        hotelList: [],
        channelList: [],
        accList: [
          { label: '当月', value: 'month' },
          { label: '当年', value: 'year' },
        ],
        currentHotel: {},
        currentAcc: 'month',
        tableList: [],
        totalSum: {},
        dataColumns: [
          {
            dataIndex: 'companyIndex',
            key: 'companyIndex',
            title: '排名',
            width: 100,
            align: 'right',
            children: [
              {
                title: 'TOP10',
                dataIndex: 'companyIndex',
                key: 'companyIndex',
                width: 100,
                align: 'center',
              },
            ],
          },
          {
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200,
            align: 'left',
            children: [
              {
                title: '公司名称',
                dataIndex: 'companyName',
                key: 'companyName',
                width: 200,
                align: 'left',
              },
            ],
          },
          {
            dataIndex: 'room',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '间夜',
                dataIndex: 'room',
                key: 'room',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'roomRate',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'roomRate',
                key: 'roomRate',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 1),
              },
            ],
          },
          {
            title: '当月实际',
            dataIndex: 'income',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '收入',
                dataIndex: 'income',
                key: 'income',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'incomeRate',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'incomeRate',
                key: 'incomeRate',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 1),
              },
            ],
          },
          {
            dataIndex: 'price',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: 'ADR',
                dataIndex: 'price',
                key: 'price',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            width: 20,
            className: 'table-header-blank',
            dataIndex: 'temp',
            key: 'temp',
            children: [
              {
                dataIndex: 'temp',
                key: 'temp',
                width: 20,
                className: 'table-header-blank',
              },
            ],
          },
          {
            title: '排名',
            width: 200,
            align: 'left',
            dataIndex: 'lCompanyName',
            key: 'lCompanyName',
            children: [
              {
                title: '公司名称',
                dataIndex: 'lCompanyName',
                key: 'lCompanyName',
                width: 200,
              },
            ],
          },
          {
            dataIndex: 'lRoom',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '间夜',
                dataIndex: 'lRoom',
                key: 'lRoom',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lRoomRate',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'lRoomRate',
                key: 'lRoomRate',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 1),
              },
            ],
          },
          {
            title: '去年同期',
            dataIndex: 'lIncome',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '收入',
                dataIndex: 'lIncome',
                key: 'lIncome',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lIncomeRate',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'lIncomeRate',
                key: 'lIncomeRate',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 1),
              },
            ],
          },
          {
            dataIndex: 'lPrice',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: 'ADR',
                dataIndex: 'lPrice',
                key: 'lPrice',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
        ],
      };
    },

    created() {
      defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }).then((res) => {
        if (res.success && res.result.length > 0) {
          const dataList = res.result;
          this.hotelList = dataList.map((s) => {
            return { label: s.name, value: s.code };
          });
          const currentHotelCode = this.$route.query.hotelCode || localStorage.getItem(Constant.STORAGE_HOTEL_NAME);
          if (currentHotelCode && dataList.filter((d) => d.code === currentHotelCode).length > 0) {
            this.currentHotel = dataList.filter((d) => d.code === currentHotelCode)[0];
          } else {
            this.currentHotel = {
              code: dataList[0].code,
              name: dataList[0].name,
            };
          }
          this.hotelSel = this.currentHotel;
          const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
          this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
          this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
          this.dataColumns[4].title = this.currentAcc === 'month' ? '当月' : '年累计';

          this.fetchData();
        }
      });
    },

    methods: {
      fetchData() {
        this.loading = true;
        Promise.all([
          defHttp.post({
            url: 'data/query',
            data: {
              labelCode: APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          }),
          defHttp.post({
            url: 'data/query',
            data: {
              labelCode: INCOME_APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          }),
        ]).then(([sourceRes, incomeRes]) => {
          if (sourceRes.datas.success && sourceRes.datas.data.length > 0 && incomeRes.datas.success) {
            const dataList = sourceRes.datas.data;
            this.totalSum = incomeRes.datas.data[0];
            this.tableList = dataList.map((d) => this.wrapTableData(d, this.totalSum));
          } else {
            this.tableList = [];
            this.totalSum = {};
          }
          localStorage.setItem(Constant.STORAGE_HOTEL_NAME, this.currentHotel.code);
          this.loading = false;
        });
      },
      wrapTableData(data, sum) {
        return {
          ...data,
          roomRate: MathUtil.safeDivide(data.room, sum.room),
          incomeRate: MathUtil.safeDivide(data.income, sum.income),
          lRoomRate: MathUtil.safeDivide(data.lRoom, sum.lRoom),
          lIncomeRate: MathUtil.safeDivide(data.lIncome, sum.lIncome),
          price: MathUtil.safeDivide(data.income, data.room),
          lPrice: MathUtil.safeDivide(data.lIncome, data.lRoom),
        };
      },
      summaryData() {
        const sum = this.tableList.reduce(
          (acc, item) => {
            acc.room += item.room;
            acc.income += item.income;
            acc.lRoom += item.lRoom;
            acc.lIncome += item.lIncome;
            return acc;
          },
          { room: 0, income: 0, lRoom: 0, lIncome: 0 }
        );
        let record = {
          companyName: '前10合计',
          lCompanyName: '前10合计',
          ...sum,
        };
        record = this.wrapTableData(record, this.totalSum);
        this.customRenderData(record, this.dataColumns);
        let trecord = {
          companyName: this.currentAcc === 'month' ? '当月合计' : '年累计合计',
          lCompanyName: this.currentAcc === 'month' ? '当月合计' : '年累计合计',
          ...this.totalSum,
        };
        trecord = this.wrapTableData(trecord, this.totalSum);
        this.customRenderData(trecord, this.dataColumns);
        return [record, trecord];
      },
      customRenderData(data, columns) {
        columns.forEach((c) => {
          if (c.customRender) {
            const value = { text: data[c.dataIndex] };
            data[c.dataIndex] = c.customRender(value);
          }
          if (c.children) {
            this.customRenderData(data, c.children);
          }
        });
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
      handleSelectChange(value) {
        this.currentHotel = {
          code: value,
          name: this.hotelList.filter((h) => h.value === value)[0].label,
        };
        const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
        this.fetchCompetData();
      },
      handleAccSelect(value) {
        const name = this.accList.filter((h) => h.value === value)[0].label;
        this.currentAcc = value;
        this.reportCode = `${REPORT_CODE}-${value}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.dataColumns[4].title = this.currentAcc === 'month' ? '当月' : '年累计';
        this.fetchData();
      },
      isMonthDisabled(current) {
        const lastMonth = dayjs().subtract(1, 'month');
        return current.isAfter(lastMonth);
      },
      handleDateSelect() {
        const name = this.accList.filter((h) => h.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      handleDataChange(val) {
        this.dateSel = val;
      },
      showFilterPopup() {
        this.filterPopup = true;
        this.dateSel = this.currentDate;
      },
      cancelFilter() {
        this.filterPopup = false;
      },
      confirmFilter() {
        this.currentDate = this.dateSel;
        this.fetchData();
        this.filterPopup = false;
      },
      handleSearch() {
        this.currentDate = this.dateSel;
        this.exportHeader[0][0] = this.hotelSel.name;
        this.exportMonthHeader[0][0] = this.hotelSel.name;
        this.exportYearHeader[0][0] = this.hotelSel.name;
        this.dailyRevenueColumns[0].title = this.hotelSel.name;
        this.yearRevenueColumns[0].title = this.hotelSel.name;
        this.fetchData();
      },
    },
  };
</script>

<style lang="less" scoped>
  .main-content {
    padding: 12px 0;
    min-height: calc(55vh);
    display: flex; /* 关键属性 */
    flex-direction: column; /* 垂直排列 */
    &-title {
      &-custom {
        color: #00b578;
      }
    }
  }

  .card-double {
    display: flex;
    margin: 12px 0 12px 0;
    justify-content: space-between;

    &-item {
      flex-basis: 48%;
    }
  }

  .interval-area {
    margin-bottom: 12px;
  }

  .select-title-space {
    width: 200px;
    margin-right: 20px;
  }

  ::v-deep .select-title .van-cell {
    color: hsl(217, 16%, 60%);
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding: unset;
    -webkit-box-pack: end;
    -ms-flex-pack: end;
    justify-content: flex-end;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    position: relative;
    background-color: #112c4d;
  }

  .popup-right {
    width: auto;

    &-content {
      height: 800px;
      width: 318px;

      &-oprate {
        display: flex;
        padding: 16px;
        justify-content: center;

        &-item {
          width: 100%;
          margin-right: 10px;
        }

        &-item:last-child {
          margin-right: 0;
        }
      }
    }
  }

  @media @desktop {
    .row-content {
      display: flex;
    }

    .main-frame-desktop-header {
      padding: 1rem;
      background: #fff;
      overflow: hidden;
    }

    .echarts {
      width: 100%;
      height: 236px;
    }

    .title-name {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 36px;
      background: #ffffff;
      -webkit-box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
      box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
      border-radius: 0.25rem;
      margin: 10px;
      font-size: 16px;
      font-weight: 600;
    }

    .flex-height {
      white-space: pre-line;
      height: 268px;
    }
    .card-flex-all {
      flex: 1 1 calc(100% - 10px);
    }
  }
</style>
